﻿using DevExpress.Mvvm;
using DevExpress.Mvvm.Native;
using HandyControl.Controls;
using HandyControl.Data;
using PlaceOrder_Client.Helper;
using PlaceOrder_Client.Models.Common;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Common;
using PlaceOrder_Shared.Models.Daily;
using Prism.DryIoc;
using Prism.Mvvm;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Input;
using static DevExpress.Office.PInvoke.Win32;
using BindableBase = Prism.Mvvm.BindableBase;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
namespace PlaceOrder_Client.ViewModels
{
    public class ChatWindowViewModel : BindableBase
    {
        private readonly string _id = Guid.NewGuid().ToString();

        #region 依赖属性
        /// <summary>
        /// 是否这个中介被占用着。
        /// </summary>
        private bool isBrokerChatMessageEnabled;

        public bool IsBrokerChatMessageEnabled
        {
            get { return isBrokerChatMessageEnabled; }
            set { isBrokerChatMessageEnabled = value; RaisePropertyChanged(); }
        }


        private string sendContent;

        public string SendContent
        {
            get { return sendContent; }
            set { sendContent = value;RaisePropertyChanged(); }
        }



        public ObservableCollection<string> QuickReplies { get; } //快捷回复
        private string chatString;

        public string ChatString
        {
            get { return chatString; }
            set { chatString = value; RaisePropertyChanged(); }
        }

        private string chatTitle;

        public string ChatTitle
        {
            get { return chatTitle; }
            set { chatTitle = value; RaisePropertyChanged(); }
        }


        private bool hasNewMessage=true;

        public bool HasNewMessage
        {
            get { return hasNewMessage=true; }
            set { hasNewMessage=value;RaisePropertyChanged(); }
        }


        private string brokerName;

        public string BrokerName
        {
            get { return brokerName; }
            set { brokerName = value;RaisePropertyChanged(); }
        }

        #endregion
        public ObservableCollection<ChatInfoModel> ChatInfos { get; set; } = new();


        #region 命令
        public DelegateCommand SendStringCmd => new(SendString);
        public DelegateCommand RefreshCommand { get; private set; }
        public DelegateCommand StartSendCommand { get; private set; }
        public DelegateCommand StopSendCommand { get; private set; }

        public DelegateCommand WindowShakeCommand => new(ShakeWindow); //窗口抖动按键


        
        public DelegateCommand<RoutedEventArgs> ReadMessageCmd => new(ReadMessage);

        private string selectedReply;

        public string SelectedReply
        {
            get { return selectedReply; }
            set { selectedReply = value;RaisePropertyChanged(); }
        }


        #endregion
        private  IDailyData _dailyData { get; set; }

        private System.Timers.Timer _testTimer;

        public int _messageCount = 0;

        public int BrokerId { get; set; }
        public ChatWindowViewModel(IDailyData dailyData,string title="")
        {
            RefreshCommand = new DelegateCommand(async () => await InitChatMessagesAsync());
            if(!string.IsNullOrEmpty(title))
            {
                BrokerId = (int)OrderListViewModel.ChatReceivers.Where(o => o.Company == title).FirstOrDefault().Brokerid;

            }
            if(OrderListViewModel.occupyBrokerInfos!=null)
            {
                HandleOccupyBrokerInfoMessage(OrderListViewModel.occupyBrokerInfos); // 处理一下
            }
           
            Messenger.Default.Unregister<List<LilyOccupyBrokerInfo>>(this, MessageToken.OccupyBrokerInfo, HandleOccupyBrokerInfoMessage);
            Messenger.Default.Register<List<LilyOccupyBrokerInfo>>(this, MessageToken.OccupyBrokerInfo, HandleOccupyBrokerInfoMessage);
            //StartSendCommand = new DelegateCommand(() =>
            //{
            //    if (_testTimer != null)
            //    {
            //        // 停止已有的定时器
            //        _testTimer.Stop();
            //        _testTimer.Dispose();
            //    }

            //    _messageCount = 0; // 重置消息计数器
            //    _messageCount++;
            //    // 初始化定时器
            //    _testTimer = new System.Timers.Timer(2500); // 每5000毫秒触发一次
            //    _testTimer.Elapsed -= OnTimerElapsed;

            //    _testTimer.Elapsed += OnTimerElapsed;
            //    _testTimer.AutoReset = true;
            //    _testTimer.Enabled = true;

            //});
            //StopSendCommand = new DelegateCommand(()=>
            //{
            //    if (_testTimer != null)
            //    {
            //        // 停止定时器
            //        _testTimer.Stop();
            //        // 释放定时器资源
            //        _testTimer.Dispose();
            //        _testTimer = null;
            //        _messageCount = 0;
            //    }
            //});





            this.ChatTitle = title;
            _dailyData = dailyData;
            QuickReplies = new ObservableCollection<string>
        { 
            "好滴，麻烦",
            "收到",
            "不要，谢谢",
            "谢谢！麻烦了",
            "撤回上一条消息，不好意思。",
            "请问上一笔成交了吗？",
            "稍等，我思考一下"
        };
            Messenger.Default.Register<string>(this, MessageToken.SendChatMessage, ReceiveTitleMessage);

            //Messenger.Default.Register<List<ChatMessage>>(this, MessageToken.SendChatMessage, ReceiveMessageList);
            Messenger.Default.Register<List<ChatMessage>>(this, MessageToken.SendChatMessage, async (messages) =>
            {
                await ReceiveMessageListAsync(messages);
            });
            //Messenger.Default.Register<ChatMessage>(this, MessageToken.NewChatMessageIn, ReceiveNewChatMessage);
            Messenger.Default.Register<string>(this, MessageToken.ClearChatWindow, _ => ClearMessages());

            InitChatMessagesAsync();
        }
        private object lockOccupyBroker = new object();
        private void HandleOccupyBrokerInfoMessage(List<LilyOccupyBrokerInfo> list)
        {
            lock(lockOccupyBroker)
            {
                var items = list.Where(o => o.Occupy == true && o.Occupyier == UserHelper.UserID).ToList();

                if(items!=null&&items.Count>0)
                {
                    foreach (var item in items)
                    {
                        if (item.BrokerId == this.BrokerId)
                        {
                            IsBrokerChatMessageEnabled = true;  //占用，即True才能发消息
                        }
                        else
                        {
                            IsBrokerChatMessageEnabled = false;
                        }
                    }
                }else
                {
                    IsBrokerChatMessageEnabled = false; 
                }
               
            }
        }

        private readonly object _lockObject = new object();
        private void OnTimerElapsed(object? sender, ElapsedEventArgs e)
        {

            lock (_lockObject)
            {
                if (!string.IsNullOrEmpty(this.SendContent))
                {
                    int brokerId = (int)OrderListViewModel.ChatReceivers
                        .Where(o => o.Company == ChatTitle)
                        .FirstOrDefault().Brokerid;

                    var message = new QuanYiOrderServerResponseClass
                    {
                        DataType = QuanYiServerBaseClass.DataTypeEnum.ChatMessage,
                        ChatMessage = SendContent + _messageCount++,
                        BrokerID = brokerId,
                        UserID = UserHelper.UserID
                    };

                    Messenger.Default.Send(message, MessageToken.SendChatMessage);
                }
            }
        }

        /// <summary>
        /// 初始化聊天消息
        /// </summary>
        /// 
        private async Task InitChatMessagesAsync()
        {
            ChatInfos?.Clear();

            if (string.IsNullOrEmpty(ChatTitle))
            {
                AppLog.WriteError("ChatTitle为空，有问题");
                return;
            }

            // 获取 ChatReceiver 对象
            var chatReceiver = OrderListViewModel.ChatReceivers.FirstOrDefault(o => o.Company == ChatTitle);
            if (chatReceiver == null)
            {
                AppLog.WriteError("未找到匹配的 ChatReceiver");
                return;
            }
            PrismApplication.Current.Dispatcher.InvokeAsync(() =>
            {
                BrokerName = chatReceiver?.FormattedTarget;
            });
           
            int brokerId = (int)chatReceiver.Brokerid;

            try
            {
                // 异步获取所有聊天消息
                var allMessageList = await UserHelper.FindConditionChatMessagesAsync(brokerId, chatReceiver.ChannelId);

                if(allMessageList == null)
                {
                    return;
                }
                // 获取当前日期
                var today = DateTime.Today;
                // 转换为 ChatInfoModel

                // 创建一个并发集合来存储结果
                var concurrentList = new ConcurrentBag<ChatInfoModel>();

                // 使用 Parallel.ForEach 进行并行处理
                // 使用 Task.Run 将并行处理移到后台线程
                await Task.Run(() =>
                {
                    Parallel.ForEach(allMessageList, chatMessage =>
                    {
                        if (chatMessage.CreateTime.Date == today)
                        {
                            var chatInfoModel = new ChatInfoModel
                            {
                                Message = chatMessage.ChatMessage,
                                Type = ChatMessageType.String,
                                Role = chatMessage.Direction == 0 ? ChatRoleType.Sender : ChatRoleType.Receiver,
                                NickName = chatMessage.Direction == 0 ? UserHelper.NickName : ChatTitle,
                                CreateTime = chatMessage.CreateTime,
                                Direction = chatMessage.Direction == 0 ? "0" : "1",
                                MessageId = chatMessage.Id,
                                BrokerId = chatMessage.BrokerId,
                                TradeId = chatMessage.TradeId.HasValue ? chatMessage.TradeId.Value : 0 // 使用默认值0处理null情况
                            };
                            concurrentList.Add(chatInfoModel);
                        }
                    });
                }).ConfigureAwait(false);
                //var chatInfoModels = allMessageList.Where(chatMessage => chatMessage.CreateTime.Date == today)
                //    .Select(chatMessage => new ChatInfoModel
                //    {
                //        Message = chatMessage.ChatMessage,
                //        Type = ChatMessageType.String,
                //        Role = chatMessage.Direction == 0 ? ChatRoleType.Sender : ChatRoleType.Receiver,
                //        NickName = chatMessage.Direction == 0 ? UserHelper.NickName : ChatTitle,
                //        CreateTime = chatMessage.CreateTime,
                //        Direction = chatMessage.Direction == 0 ? "0" : "1"
                //    }).OrderBy(t=>t.CreateTime).ToList();

                // 在UI线程上更新UI
                // 将并发集合转换为列表并按创建时间排序
                var chatInfoModels = concurrentList.OrderBy(t => t.CreateTime).ToList();
                await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                {
                    // 使用范围操作一次性更新 ChatInfos
                    ChatInfos?.Clear();
                    foreach (var item in chatInfoModels)
                    {
                        ChatInfos?.Add(item);
                    }

                    // 通知滚动到列表底部
               
                });
                ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error in InitChatMessagesAsync: {ex.Message}");
                // 记录错误并处理异常情况
                AppLog.WriteError($"Error in InitChatMessagesAsync: {ex.Message}");
            }
        }

        //private async Task InitChatMessagesAsync()
        //{
        //    ChatInfos?.Clear();

        //    if (string.IsNullOrEmpty(ChatTitle))
        //    {
        //        AppLog.WriteError("ChatTitle为空，有问题");
        //        return;
        //    }

        //    // 获取 ChatReceiver 对象
        //    var chatReceiver = OrderListViewModel.ChatReceivers.FirstOrDefault(o => o.Company == ChatTitle);
        //    if (chatReceiver == null)
        //    {
        //        AppLog.WriteError("未找到匹配的 ChatReceiver");
        //        return;
        //    }

        //    int brokerId = (int)chatReceiver.Brokerid;

        //    try
        //    {
        //        // 异步获取所有聊天消息
        //        var allMessageList = await UserHelper.FindConditionChatMessagesAsync(brokerId,OrderListViewModel.ChannelId);

        //        // 转换为 ChatInfoModel
        //        var chatInfoModels = allMessageList
        //            .Select(chatMessage => new ChatInfoModel
        //            {
        //                Message = chatMessage.ChatMessage,
        //                Type = ChatMessageType.String,
        //                Role = chatMessage.Direction == 0 ? ChatRoleType.Sender : ChatRoleType.Receiver,
        //                NickName = chatMessage.Direction == 0 ? UserHelper.NickName : ChatTitle,
        //                CreateTime = chatMessage.CreateTime,
        //                Direction = chatMessage.Direction == 0 ? "0" : "1"
        //            }).ToList();

        //        // 在UI线程上更新UI
        //        PrismApplication.Current.Dispatcher.InvokeAsync(new Action(() =>
        //        {
        //            foreach (var item in chatInfoModels)
        //            {
        //                ChatInfos.Add(item);
        //            }
        //        }));

        //        // 通知滚动到列表底部
        //        ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine($"Error in InitChatMessagesAsync: {ex.Message}");
        //        // 处理异常情况
        //    }
        //}



        private void ClearMessages()
        {
            //this.ChatInfos.Clear();
        }


        public void ScrollToBottom()
        {
            ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);
        }
        /// <summary>
        /// 收到一组消息
        /// </summary>
        /// <param name="list"></param>
        /// 
        private readonly object _receiveMessageLockObject = new object();
        private async Task ReceiveMessageListAsync(List<ChatMessage> list)
        {
            if (list == null || list.Count == 0)
            {
                Growl.InfoGlobal("当前无该中介消息");
                ChatInfos.Clear();
                return;
            }
            if (list.Count>1)
            {
                Growl.InfoGlobal("当前无该中介消息");
                AppLog.WriteError("不可能有两条消息！！");
                //ChatInfos.Clear();
                return;
            }
            HasNewMessage = true;
            // 在后台线程上执行耗时操作
            var chatInfoModels = await Task.Run(() =>
                list.Select(chatMessage => new ChatInfoModel
                {
                    Message = chatMessage.ChatMessageInfo,
                    Type = ChatMessageType.String,  // Assuming all messages are of type string
                    Role = chatMessage.Direction == 0 ? ChatRoleType.Sender : ChatRoleType.Receiver,
                    NickName = chatMessage.Direction == 0 ? UserHelper.NickName : ChatTitle,  // This may need to be adjusted based on your logic
                    CreateTime = chatMessage.CreateTime ?? DateTime.Now,
                    Direction = chatMessage.Direction == 0 ? "0" : "1",
                    MessageId=chatMessage.Id,
                    TradeId = chatMessage.TradeId,
                    BrokerId = chatMessage.BrokerId
                }).ToList()
            );

            // 检查brokerName
            string brokerName = OrderListViewModel.ChatReceivers
                .Where(o => o.Brokerid == list[0].BrokerId)
                .FirstOrDefault()?.Company;

            if (brokerName == null || brokerName != ChatTitle)
            {
                return;
            }
            lock (_receiveMessageLockObject)
            {
                // 在UI线程上更新UI
                 PrismApplication.Current.Dispatcher.Invoke(() =>
                {
                    Messenger.Default.Send(brokerName, MessageToken.ChatMessageBlink);
                    foreach (var item in chatInfoModels)
                    {
                        ChatInfos.Add(item);
                    }
                });


                ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);
                SoundPlayerHelper.PlayNotificationSound();
            }
            // 在UI线程上更新UI
            //await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
            //{
            //    Messenger.Default.Send(brokerName, MessageToken.ChatMessageBlink);
            //    foreach (var item in chatInfoModels)
            //    {
            //        ChatInfos.Add(item);
            //    }
            //});

            //// 通知滚动到列表底部
            //ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);

            //SoundPlayerHelper.PlayNotificationSound();
        }

        //private  void ReceiveMessageList(List<ChatMessage> list)
        //{
        //    if(list==null||list.Count==0)
        //    {
        //        Growl.InfoGlobal("当前无该中介消息");
        //        ChatInfos.Clear();
        //        return;
        //    }

        //    var chatInfoModels = list.Select(chatMessage => new ChatInfoModel
        //    {
        //        Message = chatMessage.ChatMessageInfo,
        //        Type = ChatMessageType.String,  // Assuming all messages are of type string
        //        Role = chatMessage.Direction == 0 ? ChatRoleType.Sender : ChatRoleType.Receiver,
        //        NickName = chatMessage.Direction == 0 ? UserHelper.NickName : ChatTitle,  // This may need to be adjusted based on your logic
        //        CreateTime = chatMessage.CreateTime ?? DateTime.Now,
        //        Direction = chatMessage.Direction == 0 ? "0" : "1"
        //    }).ToList();

        //    // Assuming ChatInfos is ObservableCollection<ChatInfoModel>
        //    string brokerName = OrderListViewModel.ChatReceivers.Where(o => o.Brokerid == list[0].BrokerId).FirstOrDefault().Company;

        //    if(brokerName==null||brokerName!=ChatTitle)
        //    {
        //        return;
        //    }
        //    PrismApplication.Current.Dispatcher.Invoke(() =>
        //    {
        //        foreach (var item in chatInfoModels)
        //        {
        //            this.ChatInfos.Add(item);
        //        }
        //    });


        //    ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);
        //}

        public event EventHandler ScrollToBottomRequested;


        //private void ReceiveMessageList(List<ChatMessage> list)
        //{
        //    var chatInfoModels = list.Select(chatMessage => new ChatInfoModel
        //    {
        //        Message = chatMessage.ChatMessageInfo,
        //        Type = ChatMessageType.String,  // Assuming all messages are of type string
        //        Role = chatMessage.Direction == 0 ? ChatRoleType.Sender : ChatRoleType.Receiver,
        //        NickName = chatMessage.Direction == 0 ? UserHelper.NickName : ChatTitle,  // This may need to be adjusted based on your logic
        //        CreateTime = chatMessage.CreateTime ?? DateTime.Now,
        //        Direction = chatMessage.Direction == 0 ? "0" : "1"
        //    }).ToList();
        //    foreach (var item in chatInfoModels)
        //    {
        //        this.ChatInfos.Add(item);
        //    }

        //    // You can now use chatInfoModels as needed
        //}


        private void ReceiveNewChatMessage(ChatMessage message)
        {

        }



        #region 具体实现
        private void ReceiveTitleMessage(string title)
        {
           // this.ChatTitle = title;
        }

        public int index = 0;
        private System.Timers.Timer _timer;
        private void StartSendTestMessage()
        {
            _timer = new System.Timers.Timer();
            _timer.Interval = 5000; // 设置为10秒，以毫秒为单位
            _timer.AutoReset = true; // 设置为true，定时器将自动重复触发
            _timer.Elapsed += TimerElapsed;
            _timer.Start();
        }
        private void TimerElapsed(object sender, ElapsedEventArgs e)
        {
            // 每隔10秒执行一次SendStringTest方法
            SendStringTest();
        }
        private void SendStringTest()
        {
            try
            {
                this.index += 5;
                var message = new QuanYiOrderServerResponseClass { DataType = QuanYiServerBaseClass.DataTypeEnum.ChatMessage, ChatMessage =UserHelper.NickName+"-index"+ index+"---"+DateTime.Now.ToString(), BrokerID = 2 };
                Messenger.Default.Send(message, MessageToken.SendChatMessage);
                AppLog.WriteInfo($"{UserHelper.NickName}发送消息{this.SelectedReply}至{ChatTitle}");

            }
            catch (Exception ex)
            {

            }
            finally
            {
                SelectedReply = null;
            }
        }

        private void SendString()
        {
            try
            {
                if (string.IsNullOrEmpty(SelectedReply)) return;
                if (string.IsNullOrEmpty(ChatTitle)) return;
                int brokerId = (int)OrderListViewModel.ChatReceivers.Where(o => o.Company == ChatTitle).FirstOrDefault().Brokerid;
                var message = new QuanYiOrderServerResponseClass { DataType = QuanYiServerBaseClass.DataTypeEnum.ChatMessage, ChatMessage = SelectedReply,BrokerID= brokerId,UserID=UserHelper.UserID};
                Messenger.Default.Send(message, MessageToken.SendChatMessage);
                AppLog.WriteInfo($"{UserHelper.NickName}发送消息{this.SelectedReply}至{ChatTitle}");

            }
            catch(Exception ex)
            {

            }
            finally
            {
               SelectedReply = null;
            }
        }


        private void ShakeWindow()
        {
            try
            {
                //if (string.IsNullOrEmpty(SelectedReply)) return;
                if (string.IsNullOrEmpty(ChatTitle)) return;
                int brokerId = (int)OrderListViewModel.ChatReceivers.Where(o => o.Company == ChatTitle).FirstOrDefault().Brokerid;
                var message = new QuanYiOrderServerResponseClass { DataType = QuanYiServerBaseClass.DataTypeEnum.ShakeWindow, ChatMessage = SelectedReply, BrokerID = brokerId, UserID = UserHelper.UserID };
                Messenger.Default.Send(message, MessageToken.ShakeWindow);
                AppLog.WriteInfo($"{UserHelper.NickName}发送消息{this.SelectedReply}至{ChatTitle}");

            }
            catch (Exception ex)
            {

            }
            finally
            {
                //SelectedReply = null;
            }
        }
        /// <summary>
        /// 发送文字
        /// </summary>
        /// <param name="e"></param>
        //private void SendString(KeyEventArgs e)
        //{
        //    if (e.Key == Key.Enter)
        //    {
        //        if (string.IsNullOrEmpty(ChatString)) return;
        //        var info = new ChatInfoModel
        //        {
        //            Message = ChatString,
        //            SenderId = _id,
        //            Type = ChatMessageType.String,
        //            Role = ChatRoleType.Sender,
        //            NickName = UserHelper.NickName,
        //            ChatTitle = "测试1",
        //            CreateTime = DateTime.Now
        //        };
        //        var info2 = new ChatInfoModel
        //        {
        //            Message = ChatString,
        //            SenderId = _id,
        //            Type = ChatMessageType.String,
        //            Role = ChatRoleType.Receiver,
        //            NickName = UserHelper.NickName,
        //            ChatTitle = "测试2",
        //            CreateTime = DateTime.Now
        //        };
        //        ChatTitle = "测试111";
        //        ChatInfos.Add(info);
        //        ChatInfos.Add(info2);
        //        Messenger.Default.Send(info, MessageToken.SendChatMessage);
        //        ChatString = string.Empty;
        //    }
        //}

        /// <summary>
        /// 读信息（音频、图片）
        /// </summary>
        /// <param name="e"></param>
        private void ReadMessage(RoutedEventArgs e)
        {
            if (e.OriginalSource is FrameworkElement { Tag: ChatInfoModel info })
            {
                if (info.Type == ChatMessageType.Image)
                {
                    //{
                    //    new ImageBrowser(new Uri(info.Enclosure.ToString()))
                    //    {
                    //        Owner = WindowHelper.GetActiveWindow()
                    //    }.Show();
                }
                else if (info.Type == ChatMessageType.Audio)
                {
                    var player = new SoundPlayer(info.Enclosure.ToString());
                    player.PlaySync();
                }
            }
        }


        private void ReceiveMessage(ChatMessage info)
        {
            //if (_id.Equals(info.SenderId)) return;
            //info.Role = ChatRoleType.Sender;
            //ChatInfos.Add(info);
        }

        int i = 0;
        public void Refresh(string brokerName)
        {
            //ChatTitle = brokerName;

        }
        #endregion
    }
}
